<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}附加费`"
    width="1400"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    destroy-on-close
  >
    <div style="height: 80vh" v-loading="loading">
      <FormTitle title="基础信息" />
      <el-form
        ref="formRef"
        :model="formValues"
        :rules="rules"
        label-position="top"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="附加费名称" prop="surcharge_name">
              <el-input
                v-model="formValues.surcharge_name"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="渠道类型" prop="channel_type">
              <el-select
                v-model="formValues.channel_type"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChannelType"
                clearable
                filterable
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in option['channel_type']"
                  :key="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物流渠道" prop="channel_ids">
              <el-select
                v-model="formValues.channel_ids"
                placeholder="请选择"
                style="width: 100%"
                multiple
                clearable
                filterable
                collapse-tags
                collapse-tags-tooltip
                @change="handleChannel"
                class="select-wrapper-style"
              >
                <el-option
                  :label="item.channel_name"
                  :value="item.id"
                  v-for="item in channelOpt"
                  :key="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="币种" prop="currency">
              <el-select
                v-model="formValues.currency"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  :label="item.label"
                  :value="item.label"
                  v-for="item in option['currency']"
                  :key="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="费用类型" prop="fee_type">
              <el-select
                v-model="formValues.fee_type"
                placeholder="请选择"
                @change="handleFeeType"
                clearable
                filterable
                class="w-[100%]"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="item in surcharge_fee_type_opt"
                  :key="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="formValues.channel_type == 1">
            <el-form-item label="仓库" prop="warehouse_ids">
              <WarehouseSelect
                placeholder="请选择目的仓库"
                v-model="formValues.warehouse_ids"
                multiple
                collapse-tags
                collapse-tags-tooltip
                wms_attribute="3,4"
                class="select-wrapper-style"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="生效时间" prop="time">
              <div class="flex">
                <el-date-picker
                  v-model="formValues.time"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="[
                    new Date(2000, 1, 1, 0, 0, 0),
                    new Date(2000, 2, 1, 23, 59, 59),
                  ]"
                />
                <el-button
                  type="primary"
                  class="ml-[-1px]"
                  @click="handleEffect"
                  >永久生效</el-button
                >
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="formValues.remark" type="textarea" />
              <div>
                说明：附加费金额 =（附加费+预估住宅费）*燃油附加费率+旺季附加费
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="4">
            <FormTitle title="明细信息" />
            <!-- <el-button type="primary" @click="handleExport">导入</el-button> -->
          </el-col>
        </el-row>
        <div class="mb-[12px]" v-for="(item, index) in cost" :key="item.key">
          <div
            class="flex items-center mb-[8px]"
            :class="{ 'border-t pt-[12px]': index != 0 }"
          >
            <span class="mr-[8px] text-[#999]">{{ index + 1 }}</span>
            <el-select
              v-model="item.destination_country"
              placeholder="到达国家"
              class="space space-width select-wrapper-style"
              multiple
              clearable
              filterable
              collapse-tags
              collapse-tags-tooltip
              style="width: 260px"
            >
              <el-option
                :label="it.label"
                :value="it.value"
                v-for="it in option['country']"
                :key="it"
              />
            </el-select>
            <el-select
              v-model="item.zip_code_ids"
              placeholder="邮编区域"
              class="space space-width select-wrapper-style"
              multiple
              clearable
              filterable
              collapse-tags
              collapse-tags-tooltip
              style="width: 300px"
            >
              <el-option
                :label="it.region_name"
                :value="it.id"
                v-for="it in option['zopCodeRegion']"
                :key="it"
              />
            </el-select>
            <div class="space">
              <el-input
                v-model="item.rule_min_value"
                placeholder="最小值"
                style="width: 150px"
                clearable
                type="number"
                :min="0"
                filterable
              >
                <template #append>{{
                  surchargeRuleTypeMap[item?.rule_type] || "cm"
                }}</template>
              </el-input>
            </div>
            <div class="space">
              &lt;
              <el-select
                v-model="item.rule_type"
                placeholder="费用类型"
                class="space-width"
                @change="(val) => handleRuleTypeChange(val, item)"
                clearable
                filterable
              >
                <el-option
                  :label="it.label"
                  :value="it.value"
                  v-for="it in option['surcharge_rule_type_opt']"
                  :key="it"
                />
              </el-select>
            </div>
            <div class="space">
              &le;
              <el-input
                v-model="item.rule_max_value"
                placeholder="最大值"
                style="width: 150px"
                clearable
                type="number"
                :min="0"
                filterable
              >
                <template #append>{{
                  surchargeRuleTypeMap[item?.rule_type] || "cm"
                }}</template>
              </el-input>
            </div>
            <div class="space">
              优先级
              <el-input
                v-model="item.priority"
                placeholder="排序"
                style="width: 60px"
                class="space"
                clearable
                type="number"
                :min="0"
                filterable
              >
              </el-input>
            </div>
            <div>
              <span
                class="hover:text-[#2080f0] cursor-pointer mr-[8px]"
                @click="handleAdd(index)"
              >
                <SvgIcon icon-class="Plus" class="text-[12px] inline" />
              </span>
              <span
                class="hover:text-[#2080f0] cursor-pointer"
                @click="handleDelete(index)"
                v-if="cost.length > 1"
                ><SvgIcon icon-class="Minus" class="text-[12px] inline" />
              </span>
            </div>
          </div>
          <div class="flex items-center">
            <div class="space">
              是否预估住宅地址费
              <el-select
                v-model="item.is_pre_hone_fee"
                placeholder=""
                class="w-[60px]"
              >
                <el-option
                  :label="it.label"
                  :value="it.value"
                  v-for="it in isMap"
                  :key="it"
                />
              </el-select>
              <el-input
                v-if="item.is_pre_hone_fee == 1"
                v-model="item.pre_hone_fee"
                placeholder="请输入金额"
                style="width: 200px"
                class="space"
                clearable
                type="number"
                :min="0"
                filterable
              >
              </el-input>
            </div>

            <div class="space">
              是否计算燃油附加费
              <el-select
                v-model="item.is_calc_fuel"
                placeholder=""
                class="w-[60px]"
              >
                <el-option
                  :label="it.label"
                  :value="it.value"
                  v-for="it in isMap"
                  :key="it"
                />
              </el-select>
            </div>
            <div class="space">
              旺季附加费
              <el-select
                v-model="item.hs_is_calc_fuel"
                placeholder=""
                class="w-[150px]"
              >
                <el-option
                  :label="it.label"
                  :value="it.value"
                  v-for="it in is_calc_fuel"
                  :key="it"
                />
              </el-select>
              <el-input
                v-model="item.hs_surcharge"
                placeholder="请输入金额"
                style="width: 200px"
                class="space"
                clearable
                type="number"
                :min="0"
                filterable
              >
              </el-input>
            </div>
          </div>
          <div class="flex items-center mt-[8px]">
            <div class="space">
              附加费
              <el-select
                v-model="item.surcharge_calc_type"
                placeholder="请选择附加费"
                class="space-width"
                style="width: 300px"
                clearable
                filterable
              >
                <el-option
                  :label="it.label"
                  :value="it.value"
                  v-for="it in getOpt(item.rule_type)"
                  :key="it"
                  :disabled="it.disabled"
                />
              </el-select>
              <el-input
                v-model="item.surcharge"
                placeholder="请输入"
                style="width: 150px"
                clearable
                type="number"
                :min="0"
                filterable
              >
                <template
                  v-if="surchargeCalcTypeMap[item?.surcharge_calc_type]"
                  #append
                  >{{
                    surchargeCalcTypeMap[item.surcharge_calc_type]
                  }}</template
                >
              </el-input>
              <el-select
                v-model="item.calc_fuel_mode"
                placeholder="请选择折扣"
                class="space-width"
                clearable
                filterable
              >
                <el-option
                  :label="it.label"
                  :value="it.value"
                  v-for="it in option['surcharge_calc_fuel_mode']"
                  :key="it"
                  :disabled="it.disabled"
                />
              </el-select>
              <el-input
                v-model="item.calc_discount_value"
                placeholder="请输入折扣"
                style="width: 150px"
                class="space"
                clearable
                type="number"
                :min="0"
                filterable
              >
              </el-input>
            </div>
            <div
              class="space"
              v-if="
                item.rule_type == 'first_weight_add_renewal' &&
                item?.first_weight_add_renewal?.length < 1
              "
            >
              <span
                class="hover:text-[#2080f0] cursor-pointer mr-[8px]"
                @click="handleAddWeight(item)"
              >
                <SvgIcon icon-class="Plus" class="text-[12px] inline" />
              </span>
            </div>
          </div>
          <template v-if="item?.first_weight_add_renewal?.length > 0">
            <ContinueWeight
              v-model="item.first_weight_add_renewal"
              :options="option"
              :surchargeCalcTypeMap="surchargeCalcTypeMap"
            />
          </template>
        </div>
      </el-form>
      <div class="h-[8px]"></div>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- <ImportDialog ref="importDialogRef" @success="handleSuccess" /> -->
</template>

<script setup lang="jsx">
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage } from "element-plus";
import FormTitle from "@/components/Form/FormTitle.vue";
import WarehouseSelect from "@/components/WarehouseSelect/index.vue";
const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  option: { type: Object, default: () => ({}) },
});
import {
  translationHeaderMap,
  translationMap,
  translateObject,
  splitChannelNames,
  createMapping,
} from "./data.js";
import ContinueWeight from "../components/continueWeight/index";
import ImportDialog from "../components/importDialog/index";
import { createSurcharge, updateSurcharge, surchargeDetail } from "../api.js";
import { isMap, is_calc_fuel } from "@/data/index.js";
import { getDatesWithTime } from "@/utils/time.js";
const { option } = toRefs(props);
const isEdit = computed(() => {
  return !!props.id;
});
const formRef = ref();
const formValues = ref({});
const loading = ref();
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
const rules = reactive({
  fee_type: [{ required: true, message: "请选择费用类型", trigger: "blur" }],
  channel_ids: [{ required: true, message: "请选择物流渠道", trigger: "blur" }],
  currency: [{ required: true, message: "请选择币种", trigger: "blur" }],
  time: [{ required: true, message: "请选择生效时间", trigger: "blur" }],
  rule_min_value: [
    { required: true, message: "请输入最小值", trigger: "blur" },
  ],
  rule_max_value: [
    { required: true, message: "请输入最大值", trigger: "blur" },
  ],
  surcharge_calc_type: [
    { required: true, message: "请选择附加费", trigger: "blur" },
  ],
  surcharge: [{ required: true, message: "请输入附加费金额", trigger: "blur" }],
  pre_hone_fee: [
    { required: true, message: "请输入预估住宅地址费", trigger: "blur" },
  ],
  surcharge_name: [
    { required: true, message: "请输入附加费名称", trigger: "blur" },
  ],
  channel_type: [
    { required: true, message: "请选择渠道类型", trigger: "blur" },
  ],
  warehouse_ids: [
    { required: true, message: "请选择目的仓库", trigger: "blur" },
  ],
});
watch(
  () => props.id,
  (val) => {
    if (val) {
      getDetail();
    }
  }
);
const surchargeRuleTypeMap = computed(() => {
  return createMapping(option.value?.["surcharge_rule_type"], "value", "unit");
});
const surchargeCalcTypeMap = computed(() => {
  return createMapping(option.value?.["surcharge_calc_type"], "value", "unit");
});
const getDetail = () => {
  loading.value = true;
  surchargeDetail({ id: props.id })
    .then((res) => {
      res?.data?.details?.forEach((item, index) => {
        item.key = item.id;
      });
      formValues.value = {
        ...res?.data,
        time: [res?.data?.start_time, res?.data?.end_time],
        start_time: undefined,
        end_time: undefined,
      };
      option.value.surcharge_calc_type = option.value?.surcharge_calc_type?.map(
        (item) => ({
          ...item,
          disabled: formValues.value.fee_type !== 8 && item.value === 5,
        })
      );
      surchargeOpt(formValues.value.channel_type);
      cost.value = res?.data?.details || [
        {
          key: 1,
          is_pre_hone_fee: 0,
          is_calc_fuel: 1,
          rule_type: "length",
          hs_is_calc_fuel: 0,
        },
      ];
    })
    .finally(() => {
      loading.value = false;
    });
};
const channelOpt = computed(() => {
  const data = option.value?.["channel"] || [];
  const { channel_type } = formValues.value;
  const filterConditions = {
    1: (item) => item.delivery_mode === 2,
    2: (item) => [1, 3].includes(item.delivery_mode),
  };

  return filterConditions[channel_type]
    ? data.filter(filterConditions[channel_type])
    : [];
});

const surcharge_fee_type_opt = computed(() => {
  const data = option.value?.["surcharge_fee_type"] || [];
  const { channel_type } = formValues.value;
  const arr = data?.filter((item) => item.channel_type == channel_type);
  return arr;
});

const handleChannelType = (val) => {
  formValues.value.channel_ids = [];
  formValues.value.fee_type = null;
  surchargeOpt(val);
  cost.value = [
    {
      key: 1,
      is_pre_hone_fee: 0,
      is_calc_fuel: 1,
      rule_type: "length",
      hs_is_calc_fuel: 0,
    },
  ];
};
const surcharge_rule = ref({});
const surchargeOpt = (val) => {
  const surcharge_calc_type = option.value?.surcharge_calc_type || [];
  const surcharge_rule_type = option.value?.surcharge_rule_type || [];
  option.value.surcharge_calc_type_opt = surcharge_calc_type?.filter(
    (item) => item.channel_type == val
  );
  option.value.surcharge_rule_type_opt = surcharge_rule_type?.filter(
    (item) => item.channel_type == val
  );
  let calc = option.value?.surcharge_calc_type_opt || [];
  let rule = option.value?.surcharge_rule_type_opt || [];
  for (let i = 0; i < rule.length; i++) {
    let key = rule[i].value;
    let surcharge_calc_type = rule[i].surcharge_calc_type;
    let result = calc?.filter((item) =>
      surcharge_calc_type?.includes(item.value)
    );
    surcharge_rule.value[key] = result;
  }
};

const getOpt = (val) => {
  const { channel_type } = formValues.value;
  if (channel_type == 2) {
    return option.value.surcharge_calc_type_opt;
  } else {
    return surcharge_rule.value[val];
  }
};
provide("getOpt", getOpt);
const cost = ref([
  {
    key: 1,
    is_pre_hone_fee: 0,
    is_calc_fuel: 1,
    rule_type: "length",
    hs_is_calc_fuel: 0,
  },
]);
const handleAdd = (index) => {
  let str = {
    key: +new Date(),
    is_pre_hone_fee: 0,
    is_calc_fuel: 1,
    hs_is_calc_fuel: 0,
    rule_type: "length",
  };
  cost.value.splice(index + 1, 0, str);
};
const handleAddWeight = (item) => {
  item.first_weight_add_renewal = [{ key: +new Date() }];
};
const handleDelete = (index) => {
  cost.value.splice(index, 1);
};
const handleEffect = () => {
  formValues.value.time = getDatesWithTime();
};
const handleRuleTypeChange = (val, item) => {
  if (val == "first_weight_add_renewal") {
    item.first_weight_add_renewal = [];
  } else {
    item.first_weight_add_renewal = null;
  }
  item.surcharge_calc_type = null;
};

const handleFeeType = (vla) => {
  const surchargeTypes = option.value?.surcharge_calc_type || [];
  option.value.surcharge_calc_type = surchargeTypes.map((type) => ({
    ...type,
    disabled: vla !== 8 && type.value === 5,
  }));
  cost.value = cost.value.map((item) => ({
    ...item,
    surcharge_calc_type:
      item.surcharge_calc_type === 5 ? null : item.surcharge_calc_type,
  }));
  surchargeOpt(formValues.value.channel_type);
};
const handleSave = async () => {
  try {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        const { time } = formValues.value;
        let data = {
          ...formValues.value,
          start_time: time[0],
          end_time: time[1],
          time: undefined,
          details: JSON.parse(JSON.stringify(cost.value || [])),
        };
        let len = data?.details?.length;
        for (let i = 0; i < len; i++) {
          if (
            data?.details[i]?.rule_min_value &&
            data?.details[i]?.rule_max_value
          ) {
            if (
              Number(data?.details[i]?.rule_min_value) >
              Number(data?.details[i]?.rule_max_value)
            ) {
              ElMessage.error(`附加费,第${i + 1}条的最小值不能大于最大值`);
              return false;
            }
          }
          const { rule_type, first_weight_add_renewal } = data?.details[i];
          if (rule_type === "first_weight_add_renewal") {
            let obj = first_weight_add_renewal.find(
              (item) => item.weight_type === "FIRST_WEIGHT"
            );
            const replacement = {
              rule_min_value: data.details[i].rule_min_value,
              rule_max_value: data.details[i].rule_max_value,
              surcharge: data.details[i].surcharge,
              surcharge_calc_type: data.details[i].surcharge_calc_type,
              calc_fuel_mode: data.details[i].calc_fuel_mode,
              calc_discount_value: data.details[i].calc_discount_value,
            };
            if (obj) {
              const index = first_weight_add_renewal.indexOf(obj);
              if (index !== -1) {
                first_weight_add_renewal[index] = replacement;
              }
            } else {
              first_weight_add_renewal.unshift(replacement);
            }
          }
        }
        const { code, message } = await (isEdit.value
          ? updateSurcharge
          : createSurcharge)({
          ...data,
        });
        console.log(code, message);
        if (code !== 200) {
          ElMessage.error(message);
          return;
        }
        ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
        handleClose(true);
      } else {
        return false;
      }
    });
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
const handleChannel = (val) => {
  if (val && val?.length) {
    let item = option.value["channel"].find((item) => item.id == val[0]);
    formValues.value.currency = item.currency;
  } else {
    formValues.value.currency = null;
  }
};

//导入
const importDialogRef = ref();
const handleExport = () => {
  importDialogRef.value?.open({
    type: "surchargeManage",
    urlType: "/out/statistic-eur-vat-tax/import-tax-bill-no",
  });
};

// const handleSuccess = (val) => {
//   const resultArray = val?.map((obj) => translateObject(obj, translationMap));
//   const header = translateObject(val[0], translationHeaderMap);
//   header.fee_type =
//     option.value?.["surcharge_fee_type"]?.find(
//       (item) => item.label == header?.fee_type
//     )?.value || null;
//   header.channel_ids = splitChannelNames(header?.channel_ids);
//   header.channel_ids =
//     header?.channel_ids?.flatMap((item) =>
//       option.value?.["channel"]
//         ?.filter((it) => it.channel_name === item)
//         ?.map((i) => i.id)
//     ) ?? [];
//   let detailId = formValues.value.id || null;
//   formValues.value = {
//     ...header,
//     id: detailId,
//   };
//   if (formValues.value.fee_type == 8) {
//     option.value.surcharge_calc_type = option.value.surcharge_calc_type?.map(
//       (item) => ({
//         ...item,
//         disabled: false,
//       })
//     );
//   } else {
//     option.value.surcharge_calc_type = option.value.surcharge_calc_type?.map(
//       (item) => ({
//         ...item,
//         disabled: item.value == 5 ? true : false,
//       })
//     );
//   }
//   resultArray?.forEach((item) => {
//     if (item?.destination_country) {
//       item.destination_country = splitChannelNames(item?.destination_country);
//     }
//     if (item?.zip_code_ids) {
//       let zip_code_data = splitChannelNames(item?.zip_code_ids);
//       zip_code_data =
//         zip_code_data?.flatMap((item) =>
//           option.value?.["zopCodeRegion"]
//             ?.filter((it) => it.region_name === item)
//             ?.map((i) => i.id)
//         ) ?? [];
//       item.zip_code_ids = zip_code_data;
//     }
//     if (item?.rule_type) {
//       let rule_type = option.value?.["surcharge_rule_type"]?.find(
//         (it) => it.label == item?.rule_type
//       );
//       item.rule_type = rule_type?.value || null;
//       item.unit = rule_type?.unit || "cm";
//     }
//     if (item?.surcharge_calc_type) {
//       let surcharge_calc_type = option.value?.["surcharge_calc_type"]?.find(
//         (it) => it.label == item?.surcharge_calc_type
//       );
//       item.surcharge_calc_type = surcharge_calc_type?.value || null;
//       item.percent = surcharge_calc_type?.unit || "";
//     }
//     item.is_pre_hone_fee = item?.is_pre_hone_fee == "是" ? 1 : 0;
//     item.is_calc_fuel = item?.is_calc_fuel == "是" ? 1 : 0;
//     item.hs_is_calc_fuel = item?.hs_is_calc_fuel == "是" ? 1 : 0;
//   });
//   cost.value = resultArray;
// };
const handleClose = async (refresh) => {
  formValues.value = {};
  cost.value = [
    {
      key: 1,
      is_pre_hone_fee: 0,
      is_calc_fuel: 1,
      hs_is_calc_fuel: 0,
      rule_type: "length",
    },
  ];
  await nextTick();
  formRef.value?.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped>
.space {
  margin-right: 8px;
}
.space-width {
  width: 150px;
}
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  // margin: 0;
}
::v-deep input[type="number"] {
  -moz-appearance: textfield;
}
</style>
